package net.maku.module.controller;

import io.swagger.v3.oas.annotations.Operation;


import net.maku.module.entity.AgStockDataDTO;
import net.maku.module.service.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.Cache;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.cache.CacheManager;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;

@RestController
@RequestMapping("/stock")
public class AgStockController {
    @Value("${gp.gpapi}")
    private String urls;

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private StockService stockService;
    @GetMapping("/getStockData")
    public ResponseEntity<AgStockDataDTO> getStockData(@RequestParam String stockCode) {

        // API 地址
//        String url = urls + "/list=" + stockCode;
//
//        // 创建 HttpHeaders，并添加 Referer
//        HttpHeaders headers = new HttpHeaders();
//        headers.set("Referer", "https://finance.sina.com.cn");
//
//        // 使用 RestTemplate 发送请求并添加自定义请求头
//        RestTemplate restTemplate = new RestTemplate();
//        ResponseEntity<String> response = restTemplate.exchange(
//                url, HttpMethod.GET,
//                new org.springframework.http.HttpEntity<>(headers),
//                String.class);
//
//        System.out.println(response.getBody());
//        AgStockDataDTO agStockDataDTO = parseStockData(response.getBody());
        // 首先尝试从缓存获取
        Cache cache = cacheManager.getCache("stockData");
        if (cache != null) {
            AgStockDataDTO cachedData = cache.get(stockCode, AgStockDataDTO.class);
            if (cachedData != null) {
                // 异步更新缓存（不阻塞当前请求）
                stockService.asyncUpdateStockData(stockCode);
                return ResponseEntity.ok(cachedData);
            }
        }

        // 缓存中没有，同步获取数据
        AgStockDataDTO stockData = stockService.fetchStockData(stockCode);
        if (stockData != null) {
            // 放入缓存
            if (cache != null) {
                cache.put(stockCode, stockData);
            }
            return ResponseEntity.ok(stockData);
        } else {
            return ResponseEntity.status(404).build();
        }

    }



}
